import {AbstractControl, FormControl, FormGroup} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';;

/*校验器符合规则 function定义全局方法*/
export function phoneValidator(control: AbstractControl): any {
  /*control.value 获取传递过来的值*/
  var myreg = /^(((13[0-9]{1}|(15[0-9]{1})|18[0-9]{1}))+\d{8})$/;
  let valid = myreg.test(control.value);
  console.log('mobile的校验结果是:' + valid);
  /*返回为空表示校验通过*/
  return valid ? null : {phone: true};
}

/*异步校验器，返回值是一个流对象*/
export function phoneAsyncValidator(control: AbstractControl): any {
  /*control.value 获取传递过来的值*/
  var myreg = /^(((13[0-9]{1}|(15[0-9]{1})|18[0-9]{1}))+\d{8})$/;
  let valid = myreg.test(control.value);
  console.log('mobile的校验结果是:' + valid);
  /*延迟五秒，模拟异步校验*/
/*  return Observable.of(valid ? null : {phone: true}).delay(5000);*/
  return Observable.create(valid ? null : {phone: true}).delay(5000);
}


export function equalValidator(group: FormGroup): any {
    let password: FormControl = group.get('password') as FormControl;
    let pconfrim: FormControl = group.get('pconfrim') as FormControl;
    let passwordValid: boolean = (password.value === pconfrim.value);
    console.log('password的校验结果：' + passwordValid);
    return passwordValid ? null : {equal: {msg: '' +
          '0.，请重新输入'}};
}
